<template>
   

    <el-avatar :size="100" :src="imgUrl" shape="square"  @click="showImg">
      <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
      />
    </el-avatar>
    <el-drawer v-model="drawer" direction="rtl" size="50%">
        <el-upload v-model:file-list="fileList" :auto-upload="false" list-type="picture-card" :on-change="onChange">
            <el-icon>
                <Plus />
            </el-icon>
            <template #file="{ file }">
                <div  @click="getImg(file)">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                        <span>
                            <el-icon><Select /></el-icon>
                        </span>
                    </span>
                </div>
            </template>
        </el-upload>

    </el-drawer>
</template>

<script lang="ts" setup>

import { onMounted, ref ,watch} from 'vue'
import { uploadApi } from '@/api'

//数据流向是单向的， 从父到子
const props =   defineProps({modelValue:{type:String, default:''}})
const emit =    defineEmits(['update:modelValue']) // 触发器，声明。提前给老爹声明一下，我待会可能用动用你的money

const fileList = ref<any>([])
const drawer = ref(false)
const imgUrl = ref('')
onMounted(() => {
  
    imgUrl.value = props.modelValue
    getFileList()
})
watch(()=>props.modelValue,(newVal,oldVal)=>{

   imgUrl.value = props.modelValue
   
})
const showImg = () => {
    drawer.value = true
}
const onChange = (uploadFile: any, _uploadFiles: any) => {
    let file = uploadFile.raw
    let name = file.name
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
        upload(name, reader.result)
    }

}
const getImg = (file: any) => {
    drawer.value = false
    imgUrl.value = file.url
 
    // props.modelValue = file.url  只读的
    emit('update:modelValue',file.url)


}
const getFileList = () => {

    uploadApi.select.call().then(res => {

        fileList.value = res
    })
}
const upload = (name: string, base64: any) => {

    uploadApi.upload.call({ name: name, base64: base64 })
        .then((res) => {
            fileList.value.pop()
            fileList.value.push({name:name,url:res})
        })

}

</script>